<template>
<div class="CMSList">
  <search-block type='flex'>
    <template slot="button">
      <el-button @click="reset">重置</el-button>
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="addCMS">添加发布模板</el-button>
    </template>
    <el-form inline :model="model">
      <el-form-item label="标题:">
        <el-input v-model="model.title" clearable></el-input>
      </el-form-item>
      <el-form-item label="发布类型:">
        <y-code-select
          clearable
          v-model="model.publishType"
          dict="cms_publish_type"></y-code-select>
      </el-form-item>
      <el-form-item label="正文类型:">
        <y-code-select
          clearable
          v-model="model.contentType"
          dict="cms_content_type"></y-code-select>
      </el-form-item>
      <el-form-item label="发布范围:">
        <y-code-select
          clearable
          v-model="model.scope"
          dict="cms_scope"></y-code-select>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns">
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="150">
      <template v-slot="scope">
        <div class="table-buttons">
          <el-button type="primary" size="mini" @click="editCMS(scope.row)">编辑</el-button>
          <el-popconfirm
              title="是否确认删除该协议？"
              @confirm="delCMS(scope.row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    v-model="forms.formModel"
    class="cms-dialog"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    force-inner-scroll
    width="900px"
    :form-attrs="forms.formAttrs"
    :columns="formColumns"
    @open="initCmsList"
    @ensure="ensureModel">
    <template slot="contentInfoList">
      <template v-if="forms.formModel.contentType === 'cms_text'">
        <el-input
          v-if="forms.formModel && Array.isArray(forms.formModel.contentInfoList) && forms.formModel.contentInfoList.length"
          v-model="forms.formModel.contentInfoList[0].content"
          type="textarea"
          :autosize="{ minRows: 3}"></el-input>
      </template>
      <template v-else-if="forms.formModel.contentType === 'cms_photo'">
        <draggable
          v-model="forms.formModel.contentInfoList"
          class="cms-photos"
          v-if="forms.formModel && Array.isArray(forms.formModel.contentInfoList)">
          <cms-photos-item
            v-for="(item, index) in forms.formModel.contentInfoList"
            :key="item.attachmentId || index"
            :model="item"
            :cms-list="cmsList"
            @add="addPhoto"
            @delete="delPhoto(index)"></cms-photos-item>
        </draggable>
      </template>
      <template v-else-if="forms.formModel.contentType === 'cms_photo_text'">
        <y-rich-text
          v-if="forms.formModel && Array.isArray(forms.formModel.contentInfoList) && forms.formModel.contentInfoList.length"
          business-sys-module-code="CMS_CONTENT"
          v-model="forms.formModel.contentInfoList[0].content"
          ></y-rich-text>
      </template>
    </template>
  </y-form>
</div>
</template>

<script>
import draggable from 'vuedraggable'
import cmsPhotosItem from "@/views/applet/CMSPhotosItem";
export default {
  name: "CMSList",
  components:{ cmsPhotosItem, draggable },
  inject: ['getDictNameSync'],
  computed:{
    /*timeVal:{
      get(){
        if(this.model.publishTime){
          return [this.model.publishTime, this.model.deadlineTime];
        }else{
          return '';
        }
      },
      set(val){
        if(Array.isArray(val) && val.length){
          [this.model.publishTime, this.model.deadlineTime] = val;
        }else{
          [this.model.publishTime, this.model.deadlineTime] = ['', ''];
        }
      }
    },*/
    formTimeVal:{
      get(){
        if(this.forms.formModel.publishTime){
          return [this.forms.formModel.publishTime, this.forms.formModel.deadlineTime];
        }else{
          return '';
        }
      },
      set(val){
        if(Array.isArray(val) && val.length){
          [this.forms.formModel.publishTime, this.forms.formModel.deadlineTime] = val;
        }else{
          [this.forms.formModel.publishTime, this.forms.formModel.deadlineTime] = ['', ''];
        }
      }
    },
    getDataWay(){
      return{
        dataType: 'url',
        data: this.$api.applet.cmsList,
        param: this.model
      }
    },

    formColumns(){
      return [
        {
          label: "标题",
          prop: "title",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        {
          label: "发布类型",
          prop: "publishType",
          comp:{
            compType: 'YCodeSelect',
            attrs: {
              dict: 'cms_publish_type'
            }
          }
        },{
          label: "正文类型",
          prop: "contentType",
          comp:{
            compType: 'YCodeSelect',
            attrs: {
              dict: 'cms_content_type',
              disabled: this.forms.formsType === 'EDIT'
            },
            listeners: {
              change: (function(val){
                this.resetContentInfoList(val)
              }).bind(this)
            }
          }
        },{
          label: "发布范围",
          prop: "scope",
          comp:{
            compType: 'YCodeSelect',
            attrs: {
              dict: 'cms_scope'
            }
          }
        },{
          label: "发布内容",
          prop: "contentInfoList",
          vIf: !!this.forms.formModel.contentType,
          template: true
        },
        {
          label: "排序",
          prop: "sort",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true
            }
          }
        }
      ]
    }
  },
  data(){
    return{
      cmsList: [],
      model:{
        publishType: '',
        contentType: '',
        scope: '',
        title: '',
        publishTime: '',
        deadlineTime: ''
      },
      columns: [{
        label: "标题",
        prop: "title"
      },{
        label: "发布类型",
        prop: "publishType",
        width: 100,
        formatter: (function(row){
          return this.getDictNameSync(row.publishType, 'cms_publish_type')
        }).bind(this)
      },{
        label: "正文类型",
        prop: "contentType",
        width: 100,
        formatter: (function(row){
          return this.getDictNameSync(row.contentType, 'cms_content_type')
        }).bind(this)
      },{
        label: "发布范围",
        prop: "scope",
        width: 100,
        formatter: (function(row){
          return this.getDictNameSync(row.scope, 'cms_scope')
        }).bind(this)
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加发布模板',
          'EDIT': '编辑发布模板'
        },
        formModel:{
          publishType: '',
          contentType: '',
          scope: '',
          title: '',
          publishTime: '',
          deadlineTime: '',
          sort: '',
          contentInfoList: []
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            publishType: [{required: true, message: "请选择发布类型", trigger: "change"}],
            contentType: [{required: true, message: "请选择正文类型", trigger: "change"}],
            scope: [{required: true, message: "请选择发布范围", trigger: "change"}],
            title: [{required: true, message: "请输入标题", trigger: "blur"}]
          }
        }
      }
    }
  },
  methods:{
    initCmsList(){
      this.$yAxios({
        url: this.$api.applet.cmsAllList,
        data: {}
      }, info => {
        this.cmsList = info;
      })
    },
    reset(){
      Object.keys(this.model).map(key => {
        this.model[key] = '';
      });
    },
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : (
          key === 'contentInfoList' ? [] : ''
        );
      })
    },
    resetContentInfoList(val){
      this.forms.formModel.contentInfoList = [];
      switch(val){
        case 'cms_text':{//文字
          this.forms.formModel.contentInfoList.push({
            content: "",
          });
          break;
        }
        case 'cms_photo':{//图片
          this.forms.formModel.contentInfoList.push({
            attachmentId: "",
            content: "",
            outerLink: "",
          });
          break;
        }
        case 'cms_photo_text':{//图片
          this.forms.formModel.contentInfoList.push({
            content: ""
          });
          break;
        }
      }
    },
    addCMS(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    editCMS(row){
      this.forms.formsType = 'EDIT';
      this.$yAxios({
        url: this.$api.applet.getCms,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$set(this.forms, 'currentForm', info);
        this.resetForm();
        if(Array.isArray(this.forms.formModel.contentInfoList)
          && this.forms.formModel.contentType === 'cms_photo'){
          this.forms.formModel.contentInfoList.push({
            attachmentId: "",
            content: "",
            outerLink: "",
          });
        }
        this.forms.showForm = true;
      })
    },
    delCMS(row){
      this.$yAxios({
        url: this.$api.applet.removeCms,
        data:{
          id: row.id
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    ensureModel(form){
      let newForm, url;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
        url = this.$api.applet.updateCms
      }else{
        newForm = Object.assign({}, form);
        url = this.$api.applet.addCms;
      }
      if(Array.isArray(newForm.contentInfoList) && newForm.contentType === 'cms_photo'){
        newForm.contentInfoList = newForm.contentInfoList.filter(item => !!item.content);
        newForm.contentInfoList.map((item, index) => {
          item.sort = index
        });
      }
      this.$yAxios({
        url,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    addPhoto(){
      this.forms.formModel.contentInfoList.push({
        attachmentId: "",
        content: "",
        outerLink: "",
      });
    },
    delPhoto(index){
      this.$delete(this.forms.formModel.contentInfoList, index);
    }
  }
}
</script>

<style scoped lang="less">
</style>
